import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { map } from 'rxjs/operators';
import { WebStorageService } from './webStorage.service';
import {LoginModel} from "../models/auth.model";

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    base = '/auth';
    constructor(private _http: HttpClient,
                private webStorageService: WebStorageService) {}

    /**
     * 获取验证码
     */
    captchaImage():Observable<any>{
        return this._http.get(environment.baseUrl + this.base + '/code');
    }

    /**
     * 获取租户列表
     */
    getTenantList(): Observable<any> {
        return this._http.get(environment.baseUrl + this.base + '/tenant/list');
    }

    /**
     * 登录验证
     */
    authLogin(data: LoginModel): Observable<any> {
        data.clientId = environment.clientId;
        return  this._http.post(environment.baseUrl + this.base  + '/login',JSON.stringify(data).toString()).pipe(map((res: any) => {
            if (res.success){
                this.webStorageService.setToken(res.data.access_token);
            }
            return res;
        }));
    }




    isLogin(){
        if (this.webStorageService.getToken() == null) {
            return false;
        }else {
            return true;
        }
    }


    /**
     * 用户注册
     */
    userRegister(queryParams: any): Observable<any> {
        return  this._http.post(environment.baseUrl + this.base + 'auth/userRegister', queryParams);
    }



    /**
     * 退出登录
     */
    logOut(): Observable<any> {
        return this._http.post(environment.baseUrl + this.base + 'auth/loginOut', '');
    }
}
